package com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.activity.Main.TempleyActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.AddProxyUserActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.bean.ObjValInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 *
 * 变更法定代表人姓名
 */
public class ChangerLegalRepActivity extends BaseCreateActivity implements OnClickListener {

    private int REQUEST_CODE_ADDRESS = 10001;
    PublicNoticeDialog noticeDialog;
//    private EditText et_Name,et_socialcode,et_fddbz,et_openbank,et_countname,et_fddbrzfzm,et_chanegenote;
private EditText et_legalrap_name, et_legalrap_phone, et_legalrap_other_phone, et_legalrap_email, et_legalrap_id, et_chanegenote;

    private TextView sendAddress,textSum;
//    private CheckBox ck_online1,ck_online2,ck_downline1,ck_downline2,ck_line2;

    private static final int TYPE_UPLOAD = 0; // 0:线上,1:线下
    private static final int TYPE_LOCAL = 1;
    private static final int TYPE_ALLGIVE = 2;
    private RecyclerView mImgRecyclerView1,mImgRecyclerView2;

    private List<UploadImage> mImgList1 = new ArrayList<>();
    private GridImagesAdapter mImgAdapter1;
    private List<UploadImage> mImgList2 = new ArrayList<>();
    private GridImagesAdapter mImgAdapter2;

    private Button top_back;
    private int provideCard = TYPE_UPLOAD; // 本人身份证提供方式
    private int providePowerAttorney = TYPE_UPLOAD; // 授权委托书提供方式


    private static final String TAG = ChangerLegalRepActivity.class.getSimpleName();


    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADDRESS) {
//                address = (AddressInfo) data.getSerializableExtra("address");
//                tvAddr.setText(address.getDetailString());
                sysAddressId = data.getStringExtra("id");
                sendAddress.setText(data.getStringExtra("desc"));
            }
        }
    }

    //    private static String mProID;
//    public static void start(Context context,MyProInfo info) {
//        Intent intent = new Intent(context, CreateProFlowActivity.class);
//        mInfo = info;
//        context.startActivity(intent);
//    }
    CommonPromptDialog mPromptDialog;

    private static ZQUserDetailBaseInfo mInfo;

    private static String mType;

    private static int mUserType;//0管理人 1 债权人

    //0 代理人基础信息录入，接口5.19，
    //1 代理人菜单操作     接口 5.30
    //2 代表人菜单操作     接口 5.19
    private static int mEntry;

    public static void start(Context context, ZQUserDetailBaseInfo info, String type, int userType,int  entry) {
        Intent intent = new Intent(context, ChangerLegalRepActivity.class);
        mInfo = info;
        mType = type;
        mUserType = userType;
        mEntry =entry;
        context.startActivity(intent);
    }

    private TextView proxy_show_temp_xts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_changer_legalcrep);
        super.onCreate(savedInstanceState);
        titlebar_title = findViewById(R.id.top_title);
        titlebar_back = findViewById(R.id.top_back);
        et_legalrap_name = findViewById(R.id.et_legalrap_name);
        et_legalrap_phone = findViewById(R.id.et_legalrap_phone);
        if(mEntry == 1)
        {
            titlebar_title.setText("变更为法定代表人操作");
            et_legalrap_name.setHint(new SpannedString("请填写法定代表人姓名"));
            et_legalrap_phone.setHint(new SpannedString("请填写法定代表人电话"));
        }else {
            titlebar_title.setText("变更为新的法定代表人操作");
            et_legalrap_name.setHint(new SpannedString("请填写变更后的法定代表人姓名"));
            et_legalrap_phone.setHint(new SpannedString("请填写变更后的法定代表人电话"));
        }

        if(mEntry ==2)
        {
           findViewById(R.id.notice_show).setVisibility(View.VISIBLE);
        }
        initViews();
        initData();


    }

    @Override
    public void onClick(View view) {


        switch (view.getId()) {


            case R.id.top_back:
                finishpage();
                break;
            default:
                break;
        }


    }

    private void initViews() {
        titlebar_back = findViewById(R.id.top_back);
        titlebar_menu_text = findViewById(R.id.top_mune1);
        titlebar_back.setOnClickListener(this);
        titlebar_menu_text.setText("提交");
        titlebar_menu_text.setVisibility(View.VISIBLE);

        titlebar_menu_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });


        et_legalrap_other_phone = findViewById(R.id.et_legalrap_other_phone);
        et_legalrap_email = findViewById(R.id.et_legalrap_email);
        et_legalrap_id = findViewById(R.id.et_legalrap_id);
        et_chanegenote = findViewById(R.id.et_chanegenote);
        sendAddress = findViewById(R.id.et_addr);
        textSum = findViewById(R.id.textSum);

        et_chanegenote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tempStr = et_chanegenote.getText().toString();
                if (tempStr.length() < 300) {
                    textSum.setText(tempStr.length() + "/300");
                } else {
                    et_chanegenote.setText(tempStr.substring(0, 300));
                    textSum.setText("300/300");
                }
            }
        });

        titlebar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        sendAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChangerLegalRepActivity.this, CreateAddrActivity.class);
                intent.putExtra(CreateAddrActivity.KEY_FROM, CreateAddrActivity.FROM_FLOW);
                startActivityForResult(intent, REQUEST_CODE_ADDRESS);
            }
        });

        proxy_show_temp_xts = findViewById(R.id.proxy_show_temp_xts);
        proxy_show_temp_xts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TempleyActivity.start(ChangerLegalRepActivity.this,1);
            }
        });


        // 营业执照提供方式
        ((RadioGroup) findViewById(R.id.rg_zqr_id_type)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int which) {
                if (which == R.id.rg_zqr_id_type_1) {
                    provideCard = TYPE_UPLOAD;
                    findViewById(R.id.area_upload_yyzz).setVisibility(View.VISIBLE);
                } else if (which == R.id.rg_zqr_id_type_2) {
                    provideCard = TYPE_LOCAL;
                    findViewById(R.id.area_upload_yyzz).setVisibility(View.GONE);
                }
            }
        });
//
//        // 法人身份证明
        ((RadioGroup) findViewById(R.id.rg_zqr_yyzz_type)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int which) {
                if (which == R.id.rg_zqr_yyzz_type_1) {
                    providePowerAttorney = TYPE_UPLOAD;
                    findViewById(R.id.area_upload_yyzz2).setVisibility(View.VISIBLE);
                } else if (which == R.id.rg_zqr_yyzz_type_2) {
                    providePowerAttorney = TYPE_LOCAL;
                    findViewById(R.id.area_upload_yyzz2).setVisibility(View.GONE);
                }else if (which == R.id.rg_zqr_yyzz_type_3) {
                    providePowerAttorney = TYPE_ALLGIVE;
                    findViewById(R.id.area_upload_yyzz2).setVisibility(View.GONE);
                }
            }
        });

        mImgRecyclerView1 = findViewById(R.id.recycler1);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView1.setLayoutManager(manager);
        mImgAdapter1 = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter1.setList(mImgList1);
        mImgRecyclerView1.setAdapter(mImgAdapter1);

        mImgRecyclerView2 = findViewById(R.id.recycler2);
        FullyGridLayoutManager manager2 = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView2.setLayoutManager(manager2);
        mImgAdapter2 = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter2.setList(mImgList2);
        mImgRecyclerView2.setAdapter(mImgAdapter2);

//        ck_online1.set

    }

//    private CommonPromptDialog mPromptDialog;
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChangerLegalRepActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }

    @Override
    public void initData() {

    }

    private boolean showflag = true;
    private String sysAddressId = ""; //邮寄地址

    public void finishpage() {
        ChangerLegalRepActivity.super.finish();
//        noticeDialog = new PublicNoticeDialog(ChangerLegalRepActivity.this, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (v.getId() == R.id.btn_save_notice) {
//                    ChangerLegalRepActivity.super.finish();
//                }
//                noticeDialog.dismiss();
//            }
//        }, 1, "提示", "放弃编辑？",
//                "否", "是");
//        noticeDialog.show();
    }



    public void saveData() {


        et_legalrap_name = findViewById(R.id.et_legalrap_name);
        et_legalrap_phone = findViewById(R.id.et_legalrap_phone);
        et_legalrap_other_phone = findViewById(R.id.et_legalrap_other_phone);
        et_legalrap_email = findViewById(R.id.et_legalrap_email);
        et_legalrap_id = findViewById(R.id.et_legalrap_id);
        sendAddress = findViewById(R.id.et_addr);




        if (TextUtils.isEmpty(et_legalrap_name.getText().toString())) {
            showToast("法定代表人姓名不可为空");
            return;
        }

        if (TextUtils.isEmpty(et_legalrap_phone.getText().toString())) {
            showToast("法定代表人电话不可为空");
            return;
        }


        if (TextUtils.isEmpty(et_legalrap_id.getText().toString())) {
            showToast("法定代表人身份证号不可为空");
            return;
        }

        int num = 0;
        int provideCardInt =0;

        if( ((RadioGroup) findViewById(R.id.rg_zqr_id_type)).getCheckedRadioButtonId() == R.id.rg_zqr_id_type_1)
        {
            provideCardInt= 0;
        }else{
            provideCardInt= 1;
        }

        for (UploadImage image : mImgList1) {
            if (TextUtils.equals(image.getFilename(), NAME_ADD)) {
                continue;
            }
            num ++;
        }

        int provideLegalRepresentativeInt =0;

        if( ((RadioGroup) findViewById(R.id.rg_zqr_yyzz_type)).getCheckedRadioButtonId() == R.id.rg_zqr_yyzz_type_1)
        {
            provideLegalRepresentativeInt= 0;
        }else if( ((RadioGroup) findViewById(R.id.rg_zqr_yyzz_type)).getCheckedRadioButtonId() == R.id.rg_zqr_yyzz_type_2){
            provideLegalRepresentativeInt= 1;
        }else{
            provideLegalRepresentativeInt = 2;
        }




        if (num == 0 && provideCardInt ==0) {
            showToast("法定代表人身份证不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//            showToast("证明文件不能为空");
            return;
        }

        num = 0;
        for (UploadImage image : mImgList2) {
            if (TextUtils.equals(image.getFilename(), NAME_ADD)) {
                continue;
            }
            num ++;
        }


        if (num == 0&& provideLegalRepresentativeInt ==0) {
            showToast("法定代表人身份证证明不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//            showToast("证明文件不能为空");
            return;
        }


//        if (mImgList1 != null && mImgList1.size() > 0) {
//            provideCardInt = "0";
//        }
//
//        String provideLegalRepresentativeInt = "1";
//        if (mImgList2 != null && mImgList2.size() > 0) {
//            provideLegalRepresentativeInt = "0";
//        }


//        if (mImgList1.size() < 1) {
//            ToastUtil.showShort("证明文件不能为空");
//            return;
//        }
//        JSONArray fileArr = new JSONArray();
//        for (int i = 0; i < mImgList1.size(); i++) {
//            fileArr.put(mImgList1.get(i).parse2JSON());
//        }

        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList1.size(); i++) {
            if (TextUtils.equals(mImgList1.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                obj.putOpt("attachmentName", "相关附件"+(i+1)+".jpg");
                obj.putOpt("attachmentDownloadAddress", mImgList1.get(i).getFilepath());
                obj.putOpt("attachmentSize", mImgList1.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList1.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }




//        JSONArray fileArr2 = new JSONArray();
//        for (int i = 0; i < mImgList2.size(); i++) {
//            fileArr2.put(mImgList2.get(i).parse2JSON());
//        }
        JSONArray fileArr2 = new JSONArray();
        for (int i = 0; i < mImgList2.size(); i++) {
            if (TextUtils.equals(mImgList2.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                obj.putOpt("attachmentName", "相关附件"+(i+1)+".jpg");
                obj.putOpt("attachmentDownloadAddress", mImgList2.get(i).getFilepath());
                obj.putOpt("attachmentSize", mImgList2.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList2.get(i).getLoadUrl());
                fileArr2.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
        Observable<JsonObject> observable;




        Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", mInfo.getBankruptcyProjectId());
        parms.put("creditorId", mInfo.getId() + "");

        parms.put("cardFileJson", fileArr.toString());
        parms.put("cardNumber", et_legalrap_id.getText().toString());
        parms.put("changeDetail", et_chanegenote.getText().toString());
        parms.put("contact", et_legalrap_phone.getText().toString());
        parms.put("email", et_legalrap_email.getText().toString());
        parms.put("legalRepresentativeName", et_legalrap_name.getText().toString());
        parms.put("mailingAddress", sendAddress.getText().toString());
        parms.put("otherContact", et_legalrap_other_phone.getText().toString());
        parms.put("provideCardInt", provideCard+"");
        parms.put("provideLegalRepresentativeInt", providePowerAttorney+"");
        parms.put("proveFileJson", fileArr2.toString());


        parms.put("type", mUserType + "");
        parms.put("sysAddressId",sysAddressId);

        if(mEntry == 0 || mEntry== 2)
        {

            Network.getAPIService()
                    .legalRepresentative(parms)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            mShapeLoadingDialog.dismiss();
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
                                super.onNext(json);
                                return;
                            }
                            RefreshEvent event = new RefreshEvent();
                            event.setType(RefreshEvent.TYPE_TALK);
                            EventBus.getDefault().post(event);
                            if(mUserType== 1)
                            {
                                noticeDialog = new PublicNoticeDialog(ChangerLegalRepActivity.this, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (v.getId() == R.id.btn_save_notice) {
                                        }
                                        noticeDialog.dismiss();
                                        finish();
                                    }
                                }, 5, "提示", "变更信息已经提交管理人审核，如有疑问，可于管理人联系。",
                                        "取消", "确认");
                                noticeDialog.show();
//                                finish();

                            }else {
//                                ToastUtil.showShort("提交成功");
                                showToast("法定代表人身份证不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.SUCCESS);
                                finish();
                            }
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mShapeLoadingDialog.dismiss();
                            super.onError(e);
                        }
                    });

        }else {
            Network.getAPIService()
                    .legalRepresentativeOp(parms)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            mShapeLoadingDialog.dismiss();
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
                                super.onNext(json);
                                return;
                            }
                            RefreshEvent event = new RefreshEvent();
                            event.setType(RefreshEvent.TYPE_TALK);
                            EventBus.getDefault().post(event);
//                            ToastUtil.showShort("提交成功");
////                            finish();
                            if(mUserType== 1)
                            {


                                noticeDialog = new PublicNoticeDialog(ChangerLegalRepActivity.this, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (v.getId() == R.id.btn_save_notice) {
                                        }
                                        noticeDialog.dismiss();
                                        finish();
                                    }
                                }, 5, "提示", "变更法定代表人信息已经提交管理人审核，如有疑问，可于管理人联系。",
                                        "取消", "确认");
                                noticeDialog.show();
//                                finish();

                            }else {
//                                ToastUtil.showShort("提交成功");
                                showToast("更改完成！", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                                finish();
                            }
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mShapeLoadingDialog.dismiss();
                            super.onError(e);
                        }
                    });
        }
    }

}

